package charlie.shop.web;

import com.charlie.beans.Users;
import com.charlie.db.DAOLocal;
import com.charlie.mail.MailLocal;
import com.charlie.mail.MailTemplate;
import com.charlie.mail.MailTemplateType;
import com.charlie.sessions.UsersFacadeLocal;
import java.io.IOException;
import java.util.Date;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * User registration servlet
 * 
 * @author Vitaliy Mostipaka <imprtat@gmail.com>
 */
@WebServlet(name = "SignUpServlet", urlPatterns = {"/signup"})
public class SignUpServlet extends HttpServlet {

    @EJB
    private UsersFacadeLocal usersFacade;  
    @EJB
    private MailLocal mail;
    @EJB
    private DAOLocal dao;

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        getServletContext().getRequestDispatcher("/signup/form.jsp").forward(request, response);
    }

    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        boolean errors = false;

        String email = request.getParameter("email");
        String first_name = request.getParameter("first_name");
        String second_name = request.getParameter("second_name");
        String password = request.getParameter("pass");
        String password2 = request.getParameter("pass2");
        String location = request.getParameter("location");

        if (!usersFacade.emailIsValid(email)) {
            errors = true;
        } else if (usersFacade.findByEmail(email) != null) {
            errors = true;
            request.setAttribute("email_exist", email);
        } else {
            request.setAttribute("email", email);
        }

        if (password == null || password.length() == 0 || !password.equals(password2)) {
            errors = true;
        }

        if (!usersFacade.nameIsValid(first_name)) {
            errors = true;
        } else {
            request.setAttribute("first_name", first_name);
        }

        if (!usersFacade.nameIsValid(second_name)) {
            errors = true;
        } else {
            request.setAttribute("second_name", second_name);
        }

        if (location == null || location.length() == 0) {
            errors = true;
        } else {
            request.setAttribute("location", location);
        }

        if (errors) {
            request.setAttribute("validate", true);
            processRequest(request, response);
            return;
        }

        Users user = new Users();
        user.setEmail(email);
        user.setPassword(password);
        user.setFirstName(first_name);
        user.setSecondName(second_name);
        user.setLocation(location);
        user.setCreationDate(new Date());
        user.setUserStatus(0);
        
        usersFacade.create(user);
       
        String hash = dao.getHash(email);
        String port = "";
        if (request.getServerPort() != 80) {
            port += ":" + request.getServerPort();
        }
        String activate_link = String.format("http://%s%s%s/activate?email=%s&hash=%s",
                request.getServerName(), port, request.getContextPath(), email, hash);
        MailTemplate tpl = new MailTemplate(MailTemplateType.ACTIVATE);
        tpl.setParametr("link", activate_link);
        tpl.setParametr("name", user.getFirstName());
        mail.send(email, "Registration in CharlieShop", tpl);
        response.setContentType("text/html;charset=UTF-8");
        getServletContext().getRequestDispatcher("/signup/complete.jsp").forward(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
        public String getServletInfo() {
        return "Sign up servlet";
    }
}
